# -*- encoding: utf-8 -*-
# @Author : lijing
# @Time : 2021/2/5 11:10
# 发送报告
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header

# 发送测试结果
def send_email_msg(msg):
    # 发送邮箱地址
    from_addr = 'lidianer@126.com'
    # 邮箱授权码，非登陆密码
    password = 'AFARVCXAGNPLCKOE'
    # 收件箱地址
    to_addr = '271904191@qq.com'
    # smtp服务器
    smtp_server = 'smtp.126.com'

    # 创建一个带附件的实例
    message = MIMEMultipart()
    message['From'] = from_addr
    message['To'] = to_addr
    subject = '应用巡检通知'
    message['Subject'] = Header(subject, 'utf-8')
    # 邮件正文内容
    message.attach(MIMEText(msg, 'plain', 'utf-8'))

    try:
        smtpObj = smtplib.SMTP(smtp_server, 25)
        smtpObj.login(from_addr, password)
        smtpObj.sendmail(from_addr, [to_addr], message.as_string())
        smtpObj.quit()
        print("邮件发送成功")
    except smtplib.SMTPException:
        print("Error: 无法发送邮件")

# 发送html测试报告
def send_email_html(report_path):
    # 发送邮箱地址
    from_addr = 'lidianer@126.com'
    # 邮箱授权码，非登陆密码
    password = 'AFARVCXAGNPLCKOE'
    # 收件箱地址
    to_addr = '271904191@qq.com'
    # smtp服务器
    smtp_server = 'smtp.126.com'

    # 创建一个带附件的实例
    message = MIMEMultipart()
    message['From'] = from_addr
    message['To'] = to_addr
    subject = '应用巡检通知'
    message['Subject'] = Header(subject, 'utf-8')
    # 邮件正文内容
    message.attach(MIMEText('邮件发送测试……', 'plain', 'utf-8'))

    # 读取附件内容，构造附件1，传送当前目录下的 html 文件
    att1 = MIMEText(open(report_path, 'rb').read(), 'html', 'utf-8')
    # # 定义发送邮件的正文、格式、编码
    # att1 = MIMEText(send_att, 'html', 'utf-8')
    att1["Content-Type"] = 'html'
    # 这里的filename可以任意写，写什么名字，邮件中显示什么名字
    att1["Content-Disposition"] = 'attachment; filename="test.html"'
    message.attach(att1)

    try:
        smtpObj = smtplib.SMTP(smtp_server,25)
        smtpObj.login(from_addr, password)
        smtpObj.sendmail(from_addr, [to_addr], message.as_string())
        smtpObj.quit()
        print("邮件发送成功")
    except smtplib.SMTPException:
        print("Error: 无法发送邮件")